<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportToExcel"
          >excel导出</el-button>
          <el-button
            v-allow="'add_excel'"
            icon="plus"
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="60">
            <template #default="{row}">
              <img :src="row.staffPhoto" width="100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template #default="{row}">
              {{ formaDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete_excel'" type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10,`${total}`]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addorEdit v-if="showDialog" @close="showDialog=false" @update-empolyee="hUpdateEmpolyee" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <!--  使用组件 -->
      <el-dialog
        :visible.sync="showDialogRole"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
// 引入组件
import AssignRole from './assignRole'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeeEnum from '@/constant/employees'
import addorEdit from './empDialog'
import dayjs from 'dayjs'
// const hireType = {}
// employeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = employeeEnum.hireType.reduce((acc, item) => {
  return { ...acc, [item.id]: item.value }
}, {})

export default {
  // 注册组件
  components: {
    addorEdit, //
    AssignRole // 分配角色
  },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false, // 显示分配角色隐藏
      page: 1, // 页数
      size: 5, // 每页条数
      list: [], // 员工列表
      total: 0, // 总数
      showDialog: false // 弹层显示隐藏
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 用户点击分配角色
    hAssignRole(id) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] || '' // hireTypEnmu:{1:'正式', '2':'非正式' }
        obj['correctionTime'] = obj['correctionTime'] || '-'
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出excel
    async  exportToExcel() {
      // 1.发送ajax获取数据
      const res = await getEmployeeList(this.page, this.size)
      console.log(res)
      const { header, data } = this.formatData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 格式化时间
    formaDate(timer) {
      return dayjs(timer).format('YYYY-MM-DD')
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 删除模块
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重发请求
        this.loadEmployeeList()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    // 实现删除
    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？')
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    // 分页控制
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(val) {
      // 从hireType中 通过id找到对应的元素的value
      // const result = employeeEnum.hireType.find((item) => item.id === val)
      // if (result) {
      //   return result.value
      // } else {
      //   return '不能确定'
      // }
      // return  ? '正式' : '非正式'
      return hireType[val] ? hireType[val] : '未知'
    },
    // 加载员工列表数据
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    }
  }
}
</script>
